#!/bin/bash
#Program:
#	This program contain some script about the project.
#Histtory
#2016/10/26 bruce First releas
#2016/10/27 bruce Second releas
##2016/11/05 bruce Thrid releas log: change the script content
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~bin
export PATH

runCommandAboutProject (){
	echo -e "跑第几个命令\n1. tcpserver\n2. queue listener\n3. commandRepeater listener\n4. node server\n5. quit"
	read num
	case $num in
	1) echo "run tcpserver"
		`nohup php artisan swoole:tcpserver start >storage/logs/tcpserver.error.log 2>&1 &`
	;;
	2) echo "run queue listener"
		`nohup php artisan queue:work --daemon --tries=3 --queue=queue --sleep=0 2>>storage/logs/queue.log &`
		break
	;;
	3) echo "run commandRepeater listener"
		`nohup php artisan queue:work --daemon --tries=3 --delay=20 --queue=commandRepeater 2>>storage/logs/queue.log &`
		break
	;;
	4) echo "node server"
		`nohup node app/App.js >storage/logs/nodejs.log 2>&1 &`
	;;
	5) echo "bye"
	esac
	echo bye!
}
while :
do
	echo -e "1. 是否杀死进程\n2. 是否跑项目相关命令\n3. quit"
	read isKill
	if [[ ${isKill} && $isKill == 1 ]];then
		while :
		do
			echo -e "进程关键字\n1. artisan\n2. node\n3. next"
			read choice
			if [ ${choice} ];then
				if [ $choice == 1 ]
				then
					proc_name="artisan"
				elif [ $choice == 2 ]
				then
					proc_name="node"
				else
					break
				fi
				proc_id=`ps -ef|grep -i ${proc_name}|grep -v "grep"|awk '{print $2}'`
				echo -e ${proc_name}\n$proc_id
				if [[ -z $proc_id ]];then
				    echo "The task is not running ! "
				else
				     echo ${proc_name}" pid:"
				     echo ${proc_id[@]}
				     echo "------kill the task!------"
				     for id in ${proc_id[*]}
				     do
				       echo ${id}
				       thread=`ps -mp ${id}|wc -l`
				       echo "threads number: "${thread}
				       kill ${id}
			       
				       if [ $? -eq 0 ];then          
				            echo "task is killed ..."
				       else
				            echo "kill task failed "
				       fi
				     done
				fi
			fi
		done
	elif [[ ${isKill} && $isKill == 2 ]];then
		runCommandAboutProject
		echo bye!
		break
	else
		echo bye!
		break
	fi
done